<template>
  <Dialog :title="dialogTitle" v-model="dialogVisible" width="1000px">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="140px"
      v-loading="formLoading"
    >
      <CardTitle :title="t('instance.form.baseInfo')" />
      <el-row>
        <el-col :span="12">
          <el-form-item :label="t('instance.fields.awardsName')" prop="awardsName">
            <el-input
              v-model="formData.awardsName"
              :placeholder="t('common.inputTextPlaceholder') + t('instance.fields.awardsName')"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <el-form-item :label="t('instance.fields.year')" prop="year">
            <el-date-picker
              v-model="formData.year"
              type="year"
              value-format="YYYY"
              :placeholder="t('common.selectTextPlaceholder') + t('instance.fields.year')"
              style="width: 100%"
            />
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 荣誉类型 -->
          <el-form-item :label="t('instance.fields.honorType')" prop="honorType">
            <el-select
              v-model="formData.honorType"
              :placeholder="t('common.selectTextPlaceholder') + t('instance.fields.honorType')"
              clearable
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.HONOR_TYPE)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
        <el-col :span="12">
          <!-- 个人/集体 -->
          <el-form-item :label="t('instance.fields.teamHonor')" prop="teamHonor">
            <el-select
              v-model="formData.teamHonor"
              clearable
            >
              <el-option
                v-for="dict in getStrDictOptions(DICT_TYPE.HONOR_TEAM_HONOR)"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="t('instance.fields.noticeUrl')" prop="noticeUrl">
        <el-input
          v-model="formData.noticeUrl"
          :placeholder="t('common.inputTextPlaceholder') + t('instance.fields.noticeUrl')"
        />
      </el-form-item>
      <CardTitle :title="t('instance.form.ruleInfo')" />
      <el-form-item :label="t('instance.fields.awardsType')" prop="awardsType">
        <el-select
          v-model="formData.templateId"
          :placeholder="t('common.selectTextPlaceholder') + t('instance.fields.awardsType')"
          :disabled="!!formData.id"
          @change="handleAwardsTypeChange"
        >
          <el-option
            v-for="(item, index) in templates"
            :key="index"
            :label="item.awardsName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-row>
        <el-col :span="8">
          <el-form-item :label="t('instance.fields.onlineApply')" prop="onlineApply">
            <el-radio-group v-model="formData.onlineApply">
              <el-radio :value="true">{{ t('common.yes') }}</el-radio>
              <el-radio :value="false">{{ t('common.no') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="16">
          <template v-if="formData.onlineApply">
            <el-form-item :label="t('instance.fields.applyTime')" prop="applyStartTime">
              <el-date-picker
                v-model="applyTime"
                type="datetimerange"
                value-format="x"
                :start-placeholder="
                  t('common.selectTextPlaceholder') + t('instance.fields.applyStartTime')
                "
                :end-placeholder="
                  t('common.selectTextPlaceholder') + t('instance.fields.applyEndTime')
                "
              />
            </el-form-item>
          </template>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item
            :label="t('instance.fields.qualificationReview')"
            prop="qualificationReview"
          >
            <el-radio-group v-model="formData.qualificationReview">
              <el-radio :value="true">{{ t('common.yes') }}</el-radio>
              <el-radio :value="false">{{ t('common.no') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :label="t('instance.fields.preliminaryEvaluation')"
            prop="preliminaryEvaluation"
          >
            <el-radio-group
              v-model="formData.preliminaryEvaluation"
              :disabled="formData.awardsType === 1"
              @change="onPreliminaryEvaluationChanged"
            >
              <el-radio :value="true">{{ t('common.yes') }}</el-radio>
              <el-radio :value="false">{{ t('common.no') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item
            :label="t('instance.fields.differenceSelection')"
            prop="differenceSelection"
          >
            <el-radio-group v-model="formData.differenceSelection">
              <el-radio :value="true">{{ t('common.yes') }}</el-radio>
              <el-radio :value="false">{{ t('common.no') }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-form-item :label="t('instance.fields.conditionJson')" prop="conditionJson">
        <el-checkbox
          v-for="(item, index) in conditionArray"
          :key="index"
          v-model="item.value"
          :label="item.label"
        />
      </el-form-item>

      <template v-if="showGraduateDateRange">
        <el-form-item :label="t('instance.fields.degreeTime')" prop="degreeStartTime">
          <el-date-picker
            v-model="degreeTime"
            type="datetimerange"
            value-format="x"
            :start-placeholder="
              t('common.selectTextPlaceholder') + t('instance.fields.degreeStartTime')
            "
            :end-placeholder="
              t('common.selectTextPlaceholder') + t('instance.fields.degreeEndTime')
            "
          />
        </el-form-item>
      </template>
      <!-- 通用设置 -->
      <el-tabs v-if="formData.awardsType === 0" v-model="activeRuleName" type="border-card">
        <el-tab-pane
          v-if="formData.preliminaryEvaluation"
          :label="t('template.initialRules')"
          name="initial"
        >
          <InstanceStageRules
            ref="initialStageRulesRef"
            :is-initial="true"
            :rules-data="initialStageRules"
          />
        </el-tab-pane>
        <el-tab-pane :label="t('template.finalRules')" name="final">
          <InstanceStageRules
            ref="finalStageRulesRef"
            :is-initial="false"
            :rules-data="finalStageRules"
          />
        </el-tab-pane>
      </el-tabs>
      <!-- 师昌绪专属设置 -->
      <InstanceScxRulesSetting v-if="formData.awardsType === 1" ref="scxFormRef" />
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading"
        >{{ t('common.ok') }}
      </el-button>
      <el-button @click="dialogVisible = false">{{ t('common.cancel') }}</el-button>
    </template>
  </Dialog>
</template>
<script setup lang="ts">
import { FormRules } from 'element-plus'
import { InstanceApi, InstanceVO } from '@/api/awards/instance'
import { TemplateApi, TemplateVO } from '@/api/awards/template'
import InstanceScxRulesSetting from '@/views/awards/instance/components/InstanceScxRulesSetting.vue'
import InstanceStageRules from '@/views/awards/instance/components/general/InstanceStageRules.vue'
import {DICT_TYPE, getStrDictOptions} from "@/utils/dict";

/** 评奖 表单 */
defineOptions({ name: 'InstanceForm' })

const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗

const defaultJson =
  '[{"key": "ustc", "label": "中国科大学籍", "value": false},{"key": "atSchoolOrAfterAugust", "label": "在校生或毕业时间(离所时间)大于去年八月份", "value": false}, {"key": "atSchoolOrJustGraduate", "label": "在校标识为在校或在校标识为离校且毕结业时间为评选年度1月1日及以后", "value": false}, {"key": "allDay", "label": "学习方式: 全日制", "value": false}, {"key": "nonDirectional", "label": "培养方式: 非定向", "value": false}, {"key": "nonInternational", "label": "学生类别为不含留学硕士&留学博士", "value": false}, {"key": "notAtSchool", "label": "在校标识: 离校", "value": false}, {"key": "graduate", "label": "学籍状态: 毕业", "value": false}, {"key": "phd", "label": "学位: 博士", "value": false}, {"key": "graduateDateRange", "label": "学位日期范围", "value": false}, {"key": "secondGrade", "label": "二年级及以上研究生", "value": false}]'
const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
const formData = ref<any>({
  id: undefined,
  templateId: undefined,
  awardsName: undefined,
  year: undefined,
  honorType: undefined,
  teamHonor: undefined,
  noticeUrl: undefined,
  onlineApply: false,
  applyStartTime: undefined,
  applyEndTime: undefined,
  conditionJson: defaultJson,
  qualificationReview: false,
  differenceSelection: false,
  preliminaryEvaluation: false,
  awardsType: undefined,
  remark: undefined,
  degreeStartTime: undefined,
  degreeEndTime: undefined
})

const formRules = reactive<FormRules>({
  awardsName: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('instance.fields.awardsName'),
      trigger: 'blur'
    }
  ],
  year: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.year'),
      trigger: 'change'
    }
  ],
  noticeUrl: [
    {
      required: true,
      message: t('common.inputTextPlaceholder') + t('instance.fields.noticeUrl'),
      trigger: 'blur'
    },
    {
      pattern: /^(https?|ftp):\/\/[^\s/$.?#].[^\s]*$/,
      message: t('common.invalidUrl'),
      trigger: 'blur'
    }
  ],
  onlineApply: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.onlineApply'),
      trigger: 'change'
    }
  ],
  applyStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.applyTime'),
      trigger: 'change'
    }
  ],
  conditionJson: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.conditionJson'),
      trigger: 'blur'
    }
  ],
  qualificationReview: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.qualificationReview'),
      trigger: 'change'
    }
  ],
  differenceSelection: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.differenceSelection'),
      trigger: 'change'
    }
  ],
  preliminaryEvaluation: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.preliminaryEvaluation'),
      trigger: 'change'
    }
  ],
  awardsType: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.awardsType'),
      trigger: 'change'
    }
  ],
  degreeStartTime: [
    {
      required: true,
      message: t('common.selectTextPlaceholder') + t('instance.fields.degreeTime'),
      trigger: 'change'
    }
  ]
})

const formRef = ref() // 表单 Ref
const scxFormRef = ref() // 师昌绪专属规则设置表单 Ref
const initialStageRulesRef = ref() // 通用初评规则设置 表单 Ref
const finalStageRulesRef = ref() // 通用终评规则设置 表单 Ref
const activeRuleName = ref('initial') // 当前选中的规则设置 Tab 名称
const initialStageRules = ref() // 通用初评规则设置
const finalStageRules = ref() // 通用终评规则设置

const applyTime = computed({
  get() {
    return [formData.value.applyStartTime, formData.value.applyEndTime]
  },
  set(value) {
    formData.value.applyStartTime = value[0] ?? undefined
    formData.value.applyEndTime = value[1] ?? undefined
  }
})

const conditionArray = ref<any[]>([])

// 是否初评单选回调
const onPreliminaryEvaluationChanged = async (value: boolean) => {
  if (value) {
    activeRuleName.value = 'initial'
    await initialStageRulesRef.value?.initData()
  } else {
    activeRuleName.value = 'final'
    await finalStageRulesRef.value?.initData()
  }
}

// 处理初评终评规则回显
const handleStageRules = async (ruleList: any[], isTemplate = false) => {
  if (!ruleList?.length) return
  ruleList.forEach((rule: any) => {
    // 如果是模板需要处理一下 id、awardsId和templateId
    if (isTemplate) {
      delete rule.templateId
      rule.id = undefined
      rule.awardsId = undefined
    }
    if (rule.judgeStage === '1') {
      initialStageRules.value = rule
    } else if (rule.judgeStage === '2') {
      finalStageRules.value = rule
    }
  })
}

const templates = ref<TemplateVO[]>([])
/** 打开弹窗 */
const open = async (type: string, id?: string) => {
  dialogVisible.value = true
  dialogTitle.value = t('action.' + type)
  formType.value = type
  resetForm()
  templates.value = await TemplateApi.getTemplateSimpleList()
  // 修改时，设置数据
  if (id) {
    formLoading.value = true
    try {
      const { instanceRules, ...data } = await InstanceApi.getInstance(id)
      formData.value = data
      if (formData.value.awardsType === 0) {
        activeRuleName.value = formData.value.preliminaryEvaluation ? 'initial' : 'final'
        await handleStageRules(instanceRules)
      }
      await nextTick()
      if (formData.value.awardsType === 0) {
        // 通用的
        initialStageRulesRef.value?.initData()
        finalStageRulesRef.value?.initData()
      }
      if (formData.value.awardsType === 1) {
        // scx的 还需要读取amount表
        scxFormRef.value?.fetchDataByAward(id)
        // formDataScx.value = (await ScxAmountApi.getScxAmountByAwardsId(formData.value.id)) ?? {}
      }
    } finally {
      formLoading.value = false
    }
  }
  conditionArray.value = JSON.parse(formData.value.conditionJson || '[]')
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调

// 处理规则提交 不处理异常 向上抛出
const submitRules = async (templateId: string, instanceId: string) => {
  const data = formData.value as unknown as TemplateVO
  // 通用规则设置
  if (data.awardsType === 0) {
    // 初评 如果有则提交
    if (data.preliminaryEvaluation) {
      await initialStageRulesRef.value.submit(instanceId)
    }
    // 终评
    await finalStageRulesRef.value.submit(instanceId)
  }
  if (data.awardsType === 1) {
    // scx的 还需要写入amount表
    await scxFormRef.value.submit(templateId, instanceId)
  }
}

const submitForm = async () => {
  const data = formData.value as unknown as InstanceVO
  // 校验表单
  try {
    await formRef.value.validate()
    if (data.awardsType === 0) {
      if (data.preliminaryEvaluation) {
        await initialStageRulesRef.value.validate()
      }
      await finalStageRulesRef.value.validate()
    }
    if (data.awardsType === 1) {
      await scxFormRef.value.validate()
    }
  } catch {
    message.error(t('template.submitTips'))
    return
  }
  // 提交请求
  formLoading.value = true
  try {
    data.conditionJson = JSON.stringify(conditionArray.value)
    // 找到选择的奖项(模版)
    const template = templates.value.find((item) => item.awardsType === data.awardsType)
    // 克隆一份scx的额外数据(这里可能不是scx 无所谓执行也没事)
    // const dataScx = formDataScx.value as unknown as ScxAmountVO
    // // 每次更新都挂上奖项ID
    // dataScx.templateId = template!.id

    if (formType.value === 'create') {
      // 创建新评奖(实例)
      const instanceId = await InstanceApi.createInstance(data)
      await submitRules(template!.id, instanceId)
      // if (data.awardsType === 1) {
      //   // scx的评奖 还需要写入amount表 记录主键
      //   dataScx.awardId = instanceId
      //   // 同时创建scx
      //   await ScxAmountApi.createScxAmount(dataScx)
      // }
      message.success(t('common.createSuccess'))
    } else {
      // 更新数据
      await InstanceApi.updateInstance(data)
      await submitRules(template!.id, data.id)
      // if (data.awardsType === 1) {
      //   // scx的 还需要更新amount表
      //   const dataScx = formDataScx.value as unknown as ScxAmountVO
      //   // 判断是否有scx 可能是之前不是scx 这次后改的
      //   if (dataScx.id) {
      //     await ScxAmountApi.updateScxAmount(dataScx)
      //   } else {
      //     dataScx.awardId = data.id
      //     await ScxAmountApi.createScxAmount(dataScx)
      //   }
      // }
      message.success(t('common.updateSuccess'))
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
    formLoading.value = false
  }
}

// 重置规则相关
const resetRule = () => {
  scxFormRef.value?.resetForm()
  initialStageRulesRef.value?.resetForm()
  finalStageRulesRef.value?.resetForm()

  activeRuleName.value = 'initial'
  initialStageRules.value = undefined
  finalStageRules.value = undefined
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    templateId: undefined,
    awardsName: undefined,
    year: undefined,
    noticeUrl: undefined,
    onlineApply: false,
    applyStartTime: undefined,
    applyEndTime: undefined,
    conditionJson: defaultJson,
    qualificationReview: false,
    differenceSelection: false,
    preliminaryEvaluation: false,
    awardsType: undefined,
    remark: undefined,
    degreeStartTime: undefined,
    degreeEndTime: undefined
  }
  formRef.value?.resetFields()
  resetRule()
}

const handleAwardsTypeChange = async (templateId: string) => {
  resetRule() // 重置规则相关
  // 找到选择的模版
  const template = templates.value.find((item) => item.id === templateId)
  if (!template) {
    return
  }
  // 将模版上的默认值带入
  formData.value.templateId = template.id
  formData.value.awardsType = template.awardsType
  formData.value.onlineApply = template.onlineApply
  formData.value.qualificationReview = template.qualificationReview
  formData.value.differenceSelection = template.differenceSelection
  formData.value.preliminaryEvaluation = template.preliminaryEvaluation
  formData.value.conditionJson = template.conditionJson
  formData.value.honorType = template.honorType
  formData.value.teamHonor = template.teamHonor
  conditionArray.value = JSON.parse(formData.value.conditionJson || '[]')

  // 通用的
  if (template.awardsType === 0) {
    const rules = await TemplateApi.getTemplateRules(template.id)
    await handleStageRules(rules, true)
    await nextTick()
    initialStageRulesRef.value?.initData()
    finalStageRulesRef.value?.initData()
    // 如果没有初评规则，则默认展示终评规则tab
    if (!initialStageRules.value) {
      activeRuleName.value = 'final'
    }
  }

  // 选择了scx 加载scx的默认配置
  if (template.awardsType === 1) {
    scxFormRef.value?.fetchDataByTemplate(template.id)
  }
}

const showGraduateDateRange = computed(() => {
  // 判断是否有学位日期范围的条件
  return conditionArray.value.some((item) => item.key === 'graduateDateRange' && item.value)
})

const degreeTime = computed({
  get() {
    return [formData.value.degreeStartTime, formData.value.degreeEndTime]
  },
  set(value) {
    formData.value.degreeStartTime = value[0] ?? undefined
    formData.value.degreeEndTime = value[1] ?? undefined
  }
})
</script>
